package com.handu.luna.boss.controller;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import javax.validation.Valid;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.handu.luna.core.domain.goods.Album;
import com.handu.luna.core.domain.goods.Attribute;
import com.handu.luna.core.domain.goods.Category;
import com.handu.luna.core.domain.goods.Goods;
import com.handu.luna.core.domain.goods.GoodsAttribute;
import com.handu.luna.core.domain.goods.SKU;
import com.handu.luna.core.domain.goods.goodsMatch.GoodsMatch;
import com.handu.luna.core.domain.search.GoodsSearchCondition;
import com.handu.luna.core.domain.searchVo.GoodsSearch;
import com.handu.luna.core.domain.support.FileUploadSupport;
import com.handu.luna.core.domain.support.FileUploadSupport.ImageType;

@Controller
@RequestMapping("/goods/goods/*")
public class GoodsController extends BaseController {

	/**
	 * 全部商品
	 * 
	 * @param pageable
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "index", method = RequestMethod.GET)
	public BossModel index(
			String viewState,
			@PageableDefault(page = 0, size = DEFAULT_PAGE_SIZE, sort = "createdDate", direction = Direction.DESC) Pageable pageable)
			throws UnsupportedEncodingException {
		GoodsSearch search = null;
		List<Category> cateList = context.getCategoryRepository().findAll();
		/* cateList.add(0,new Category(0,"顶级分类")); */
		if (viewState != null && !viewState.trim().equals("")) {
			// 解析传递过来的查询json字符串
			search = (GoodsSearch) JSONObject.toBean(JSONObject
					.fromObject(new String(Base64.getDecoder()
							.decode(viewState), "UTF-8")), GoodsSearch.class);
			return createModel("/goods/goods/index")
					.add("goodsSearch", search)
					.add("goodsPage",
							context.getGoodsRepository().findAll(
									new Goods().selectCondition(search),
									pageable))
					.add("brands", context.getBrandRepository().findAll())
					.add("categorys", cateList).add("viewState", viewState);
		} else {
			search = new GoodsSearch();
			return createModel("/goods/goods/index").add("goodsSearch", search)
					.add("goodsPage", new Goods().findAll(pageable))
					.add("brands", context.getBrandRepository().findAll())
					.add("categorys", cateList).add("viewState", "");

		}
	}

	/**
	 * 分类商品
	 * 
	 * @param pageable
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "index/{id}", method = RequestMethod.GET)
	public BossModel index(
			@PathVariable long id,
			@PageableDefault(page = 0, size = DEFAULT_PAGE_SIZE, sort = "createdDate", direction = Direction.DESC) Pageable pageable)
			throws UnsupportedEncodingException {

		GoodsSearch search = new GoodsSearch();
		List<Category> cateList = context.getCategoryRepository().findAll();
		/* cateList.add(0,new Category(0,"顶级分类")); */
		if (id != 0) {
			search.setGoodsCategoryId(String.valueOf(id));
			return createModel("/goods/goods/index")
					.add("goodsSearch", search)
					.add("goodsPage",
							context.getGoodsRepository().findAll(
									new Goods().selectCondition(search),
									pageable))
					.add("brands", context.getBrandRepository().findAll())
					.add("categorys", cateList)
					.add("viewState",
							Base64.getEncoder().encodeToString(
									JSONObject.fromObject(search).toString()
											.getBytes("UTF-8")));
		} else {
			return createModel("/goods/goods/index")
					.add("goodsSearch", search)
					.add("goodsPage", new Goods().findAll(pageable))
					.add("brands", context.getBrandRepository().findAll())
					.add("categorys", cateList)
					.add("viewState",
							Base64.getEncoder().encodeToString(
									JSONObject.fromObject(search).toString()
											.getBytes("UTF-8")));
		}

	}

	/**
	 * 点击click查询 返回的时候需对查询参数封装 方便翻页传参 翻页处理对参数进行拆解
	 * 
	 * @param name
	 *            商品名称
	 * @param brandtype
	 *            商品类型
	 * @param pageable
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "index", method = RequestMethod.POST)
	public BossModel index(
			GoodsSearch GoodsSearch,
			@PageableDefault(page = 0, size = DEFAULT_PAGE_SIZE, sort = "createdDate", direction = Direction.DESC) Pageable pageable)
			throws UnsupportedEncodingException {
		List<Category> cateList = context.getCategoryRepository().findAll();
		/* cateList.add(0,new Category(0,"顶级分类")); */
		return createModel("/goods/goods/index")
				.add("goodsPage",
						context.getGoodsRepository().findAll(
								new Goods().selectCondition(GoodsSearch),
								pageable))
				.add("brands", context.getBrandRepository().findAll())
				.add("categorys", cateList)
				.add("goodsSearch", GoodsSearch)
				.add("viewState",
						Base64.getEncoder().encodeToString(
								JSONObject.fromObject(GoodsSearch).toString()
										.getBytes("UTF-8")));
	}

	/**
	 * 跳转
	 * 
	 * 跳转到添加页面
	 */
	@RequestMapping(value = "add")
	public BossModel add() {
		return createGoodsModel(new Goods());
	}
	
	/**
	 * 跳转  
	 * 
	 * 跳转到促销标题管理页面
	 * @return
	 */
	@RequestMapping(value = "editTitle")
	public BossModel editTitle() {
		return this.buildEditTitleModel("/goods/goods/editTitle");
				
	}
	
	/**
	 * 创建促销标题管理页面需要的信息
	 * @param url
	 * @return
	 */
	private BossModel buildEditTitleModel(String url){
		List<Category> categories = context.getCategoryRepository().findAll();
		return this.createModel(url).
				add("brands", context.getBrandRepository().findAll()).
				add("categorys", categories).
				add("ourcategorys", categories).
				add("goods", new Goods()).
				add("searchCondition", new GoodsSearchCondition(GoodsSearchCondition.SearchType.MATCH));

	}
	
	/**
	 * 根据品牌ID和类型ID 或者 根据选择的商品序号 进行副标题的批量修改
	 * @param goods
	 * @return
	 */
	@RequestMapping(value = "editTitleByConditions",method = RequestMethod.POST)
	@InitBinder(value = {"brandId","categoryId","title"})
	public BossModel editTitleByConditions(Goods goods) {
		long brandId = goods.getBrandId();
		long categoryId = goods.getCategoryId();
		String title = goods.getTitle();
		String goodsIds = goods.getGoodsSizeIds();//为了方便 将商品序号集字符串放到Goods类的goodsSizeIds字段中
		
		//判断是哪种方式修改
		if (StringUtils.isNotBlank(goodsIds)) {
			String[] temps = goodsIds.split(",");
			List<Long> goodsIdsL = new ArrayList<>(temps.length);
			for (String str : temps) {
				goodsIdsL.add(Long.parseLong(str));
			}
			context.getGoodsRepository().updateTitleByGoodsId(goodsIdsL, title);
		} else {
			Collection<Long> catagoryIds = null;
			//如果品牌或者类型有一方为空  则按照不为空的一种进行修改
			/*
			 * 有下列几种组合方式 
			 * 品牌为0  类型不为0 
			 * 品牌不为0  类型为0 
			 * 品牌、类型都为0 
			 * 品牌、类型都不为0
			 */
			catagoryIds = context.getCategoryRepository().getAllAndSelfCatIdByParentCollection(String.valueOf(categoryId));
			if(catagoryIds.size() == 0){
				if(brandId == 0)
					//全部修改
					context.getGoodsRepository().updateTitle(title);
				else
					//按品牌修改
					context.getGoodsRepository().updateTitleByBrandId(brandId,title);
			}else{
				if(brandId == 0)
					//全部修改
					context.getGoodsRepository().updateTitleByCatagoryIds(catagoryIds, title);
				else
					//按类型和品牌修改
					context.getGoodsRepository().updateTitleByBrandAndType(brandId, catagoryIds, title);
			}
			
			
		}
		return this.buildEditTitleModel("/goods/goods/editTitle").add("message", "批量修改商品副标题成功!");
	}

	@RequestMapping(value = "list")
	public BossModel list(long id) {

		List<Category> cateList = context.getCategoryRepository()
				.getAllByCatIdNew(String.valueOf(id));

		if (cateList.size() == 0) {
			Category cate = context.getCategoryRepository().findOne(id);
			// List<Category> cateList =
			// context.getCategoryRepository().getAllByCatIdNew(String.valueOf(id));
			String str = cate.getAttributeIds();
			String single = "";
			String only = "";
			if (str != null && !str.isEmpty()) {
				String[] strs = cate.getAttributeIds().split(",");
				for (int i = 0; i < strs.length; i++) {
					Attribute attr = context.getAttributeRepository().findOne(
							Long.valueOf(strs[i]));
					if ("SINGLE" == attr.getSelectType().toString()) {
						single += strs[i] + ",";
					} else if ("ONLY" == attr.getSelectType().toString()) {
						only += strs[i] + ",";
					}
				}
			}
			// 单选属性
			Map<String, Map<String, String>> attrMapColor = new LinkedHashMap<String, Map<String, String>>();
			Map<String, List<String>> attrMapOne = new LinkedHashMap<String, List<String>>();
			Map<String, List<String>> attrMapTwo = new LinkedHashMap<String, List<String>>();
			List<String> attrListOne = new ArrayList<String>();
			Map<String, String> attrListColor = new LinkedHashMap<String, String>();
			List<String> attrListTwo = new ArrayList<String>();
			if (single.length() != 0) {
				String[] singleList = single.split(",");
				for (int j = 0; j < singleList.length; j++) {
					Attribute attr = context.getAttributeRepository().findOne(
							Long.valueOf(singleList[j]));
					if ("颜色".equals(attr.getName())) {
						String[] inputList = attr.getInputValues().split("\n");
						if (j == 0) {
							for (int k = 0; k < inputList.length; k++) {
								String[] inputColor = inputList[k].split(",");
								attrListColor.put(inputColor[0], inputColor[1]);
							}
							attrMapColor.put(attr.getName(), attrListColor);
						} else if (j == 1) {
							for (int l = 0; l < inputList.length; l++) {
								attrListTwo.add(inputList[l]);
							}
							attrMapTwo.put(attr.getName(), attrListTwo);
						}
					} else {
						String[] inputList = attr.getInputValues().split("\n");
						if (j == 0) {
							for (int k = 0; k < inputList.length; k++) {
								attrListOne.add(inputList[k]);
							}
							attrMapOne.put(attr.getName(), attrListOne);
						} else if (j == 1) {
							for (int l = 0; l < inputList.length; l++) {
								attrListTwo.add(inputList[l]);
							}
							attrMapTwo.put(attr.getName(), attrListTwo);
						}
					}

				}
			}
			// 唯一属性
			Map<String, List<String>> attrMapThree = new LinkedHashMap<String, List<String>>();
			List<String> attrListThree;
			if (only.length() != 0) {
				String[] onlyList = only.split(",");
				for (int i = 0; i < onlyList.length; i++) {
					Attribute attr = context.getAttributeRepository().findOne(
							Long.valueOf(onlyList[i]));
					String[] inputList = attr.getInputValues().split("\n");
					attrListThree = new ArrayList<String>();
					for (int j = 0; j < inputList.length; j++) {
						attrListThree.add(inputList[j].trim());
					}
					attrMapThree.put(attr.getName(), attrListThree);
				}
			}

			String val = "ajax";
			return createModel("/goods/goods/sku_table")
					.add("attrMapOne", attrMapOne)
					.add("attrMapColor", attrMapColor)
					.add("attrMapTwo", attrMapTwo)
					.add("attrMapThree", attrMapThree).add("val", val);
		} else {
			return createModel("/goods/goods/sku_table").add("cate", "cate");
		}

		// createModel("/goods/goods/sku_table").add("goods",
		// new
		// Goods())
		// .add("attributeListColor",attributeListColor).add("attributeListSize",attributeListSize);
	}

	/**
	 * 商品编辑页面
	 * 
	 * @param id
	 * 
	 */
	@RequestMapping(value = "edit/{id}", method = RequestMethod.GET)
	public BossModel edit(@PathVariable long id) {
		Goods goods = new Goods().findOne(id);
		Category cate = context.getCategoryRepository().findOne(
				goods.getCategoryId());
		List<SKU> skuList = context.getSkuRepository().findByGoodsId(id);
		List<String> attrList = new ArrayList<String>();
		List<GoodsAttribute> goodsAttributeList = context
				.getGoodsAttributeRepository().findByGoodsId(id);
		List<String> goodsAttrList = new ArrayList<String>();
		for (GoodsAttribute goodAttr : goodsAttributeList) {
			Attribute attr = context.getAttributeRepository()
					.findByInputValues(goodAttr.getAttributeValues());
			if (attr.getName().equals("颜色")) {
				goodsAttrList.add(goodAttr.getAttributePic());
			}
		}

		String str = cate.getAttributeIds();
		String single = "";
		String only = "";
		if (str != null && !"".equals(str)) {
			String[] strs = str.split(",");
			for (int i = 0; i < strs.length; i++) {
				Attribute attr = context.getAttributeRepository().findOne(
						Long.valueOf(strs[i]));
				if ("SINGLE" == attr.getSelectType().toString()) {
					single += strs[i] + ",";
				} else if ("ONLY" == attr.getSelectType().toString()) {
					only += strs[i] + ",";
				}
			}
		}
		// 单选属性
		Map<String, Map<String, String>> attrMapColor = new LinkedHashMap<String, Map<String, String>>();
		Map<String, List<String>> attrMapOne = new LinkedHashMap<String, List<String>>();
		Map<String, List<String>> attrMapTwo = new LinkedHashMap<String, List<String>>();
		Map<String, String> attrListColor = new LinkedHashMap<String, String>();
		List<String> attrListOne = new ArrayList<String>();
		List<String> attrListTwo = new ArrayList<String>();
		if (single.length() != 0) {
			String[] singleList = single.split(",");
			for (int j = 0; j < singleList.length; j++) {
				Attribute attr = context.getAttributeRepository().findOne(
						Long.valueOf(singleList[j]));
				if ("颜色".equals(attr.getName())) {
					String[] inputList = attr.getInputValues().split("\n");
					if (j == 0) {
						for (int k = 0; k < inputList.length; k++) {
							String[] inputColor = inputList[k].split(",");
							attrListColor.put(inputColor[0], inputColor[1]);
						}
						attrMapColor.put(attr.getName(), attrListColor);
					} else if (j == 1) {
						for (int l = 0; l < inputList.length; l++) {
							attrListTwo.add(inputList[l]);
						}
						attrMapTwo.put(attr.getName(), attrListTwo);
					}
				} else {
					String[] inputList = attr.getInputValues().split("\n");
					if (j == 0) {
						for (int k = 0; k < inputList.length; k++) {
							attrListOne.add(inputList[k]);
						}
						attrMapOne.put(attr.getName(), attrListOne);
					} else if (j == 1) {
						for (int l = 0; l < inputList.length; l++) {
							attrListTwo.add(inputList[l]);
						}
						attrMapTwo.put(attr.getName(), attrListTwo);
					}
				}

			}
		}
		// 唯一属性
		Map<String, List<String>> attrMapThree = new LinkedHashMap<String, List<String>>();
		List<String> attrListThree;
		if (only.length() != 0) {
			String[] onlyList = only.split(",");
			for (int i = 0; i < onlyList.length; i++) {
				Attribute attr = context.getAttributeRepository().findOne(
						Long.valueOf(onlyList[i]));
				String[] inputList = attr.getInputValues().split("\n");
				attrListThree = new ArrayList<String>();
				for (int j = 0; j < inputList.length; j++) {
					attrListThree.add(inputList[j].trim());
				}
				attrMapThree.put(attr.getName(), attrListThree);
			}
		}
		// 回显唯一属性
		List<GoodsAttribute> goodsAttribute = context
				.getGoodsAttributeRepository().findByGoodsId(goods.getId());
		Attribute attrOnly = null;
		List<String> onlyList = new ArrayList<String>();
		for (GoodsAttribute goodsAttr : goodsAttribute) {
			attrOnly = context.getAttributeRepository().findOne(
					Long.valueOf(goodsAttr.getAttributeId()));
			if ("ONLY" == attrOnly.getSelectType().toString()) {
				onlyList.add(goodsAttr.getAttributeValues());
			} else if ("SINGLE" == attrOnly.getSelectType().toString()) {
				attrList.add(goodsAttr.getAttributeName());
			}

		}
		String val = "edit";
		return createGoodsModel(goods).add("skuList", skuList)
				.add("attrList", attrList).add("goodsAttrList", goodsAttrList)
				.add("onlyList", onlyList).add("attrMapOne", attrMapOne)
				.add("attrMapColor", attrMapColor)
				.add("attrMapTwo", attrMapTwo)
				.add("attrMapThree", attrMapThree).add("val", val);

	}

	/**
	 * 货号相同编辑页面
	 * 
	 * @param goodsSN
	 * 
	 */
	@RequestMapping(value = "editBygoodsSN/{goodsNum}", method = RequestMethod.POST)
	public BossModel editBygoodsSN(@PathVariable String goodsNum) {

		Goods good = new Goods().findOne(context.getGoodsRepository()
				.findByGoodsSN(goodsNum).get(0).getId());
		Goods goods = new Goods().findOne(good.getId());
		Category cate = context.getCategoryRepository().findOne(
				goods.getCategoryId());
		List<SKU> skuList = context.getSkuRepository().findByGoodsId(
				good.getId());
		List<String> attrList = new ArrayList<String>();
		List<GoodsAttribute> goodsAttributeList = context
				.getGoodsAttributeRepository().findByGoodsId(good.getId());
		List<String> goodsAttrList = new ArrayList<String>();
		for (GoodsAttribute goodAttr : goodsAttributeList) {
			Attribute attr = context.getAttributeRepository()
					.findByInputValues(goodAttr.getAttributeValues());
			if (attr.getName().equals("颜色")) {
				goodsAttrList.add(goodAttr.getAttributePic());
			}
		}

		String str = cate.getAttributeIds();
		String single = "";
		String only = "";
		if (str != null) {
			String[] strs = str.split(",");
			for (int i = 0; i < strs.length; i++) {
				Attribute attr = context.getAttributeRepository().findOne(
						Long.valueOf(strs[i]));
				if ("SINGLE" == attr.getSelectType().toString()) {
					single += strs[i] + ",";
				} else if ("ONLY" == attr.getSelectType().toString()) {
					only += strs[i] + ",";
				}
			}
		}
		// 单选属性
		Map<String, Map<String, String>> attrMapColor = new LinkedHashMap<String, Map<String, String>>();
		Map<String, List<String>> attrMapOne = new LinkedHashMap<String, List<String>>();
		Map<String, List<String>> attrMapTwo = new LinkedHashMap<String, List<String>>();
		Map<String, String> attrListColor = new LinkedHashMap<String, String>();
		List<String> attrListOne = new ArrayList<String>();
		List<String> attrListTwo = new ArrayList<String>();
		if (single.length() != 0) {
			String[] singleList = single.split(",");
			for (int j = 0; j < singleList.length; j++) {
				Attribute attr = context.getAttributeRepository().findOne(
						Long.valueOf(singleList[j]));
				if ("颜色".equals(attr.getName())) {
					String[] inputList = attr.getInputValues().split("\n");
					if (j == 0) {
						for (int k = 0; k < inputList.length; k++) {
							String[] inputColor = inputList[k].split(",");
							attrListColor.put(inputColor[0], inputColor[1]);
						}
						attrMapColor.put(attr.getName(), attrListColor);
					} else if (j == 1) {
						for (int l = 0; l < inputList.length; l++) {
							attrListTwo.add(inputList[l]);
						}
						attrMapTwo.put(attr.getName(), attrListTwo);
					}
				} else {
					String[] inputList = attr.getInputValues().split("\n");
					if (j == 0) {
						for (int k = 0; k < inputList.length; k++) {
							attrListOne.add(inputList[k]);
						}
						attrMapOne.put(attr.getName(), attrListOne);
					} else if (j == 1) {
						for (int l = 0; l < inputList.length; l++) {
							attrListTwo.add(inputList[l]);
						}
						attrMapTwo.put(attr.getName(), attrListTwo);
					}
				}

			}
		}
		// 唯一属性
		Map<String, List<String>> attrMapThree = new LinkedHashMap<String, List<String>>();
		List<String> attrListThree;
		if (only.length() != 0) {
			String[] onlyList = only.split(",");
			for (int i = 0; i < onlyList.length; i++) {
				Attribute attr = context.getAttributeRepository().findOne(
						Long.valueOf(onlyList[i]));
				String[] inputList = attr.getInputValues().split("\n");
				attrListThree = new ArrayList<String>();
				for (int j = 0; j < inputList.length; j++) {
					attrListThree.add(inputList[j].trim());
				}
				attrMapThree.put(attr.getName(), attrListThree);
			}
		}
		// 回显唯一属性
		List<GoodsAttribute> goodsAttribute = context
				.getGoodsAttributeRepository().findByGoodsId(goods.getId());
		Attribute attrOnly = null;
		List<String> onlyList = new ArrayList<String>();
		for (GoodsAttribute goodsAttr : goodsAttribute) {
			attrOnly = context.getAttributeRepository().findOne(
					Long.valueOf(goodsAttr.getAttributeId()));
			if ("ONLY" == attrOnly.getSelectType().toString()) {
				onlyList.add(goodsAttr.getAttributeValues());
			} else if ("SINGLE" == attrOnly.getSelectType().toString()) {
				attrList.add(goodsAttr.getAttributeName());
			}

		}
		String val = "edit";
		return createGoodsModel(goods).add("skuList", skuList)
				.add("attrList", attrList).add("goodsAttrList", goodsAttrList)
				.add("onlyList", onlyList).add("attrMapOne", attrMapOne)
				.add("attrMapColor", attrMapColor)
				.add("attrMapTwo", attrMapTwo)
				.add("attrMapThree", attrMapThree).add("val", val);

	}

	/**
	 * 回收站商品
	 * 
	 * @param pageable
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "indexTrash", method = RequestMethod.GET)
	public BossModel indexTrash(
			String viewState,
			@PageableDefault(page = 0, size = DEFAULT_PAGE_SIZE) Pageable pageable)
			throws UnsupportedEncodingException {
		return createModel("/goods/goods/trash/index").add("goodsPage",
				new Goods().findTrash(pageable)).add("viewState", "");
	}

	/**
	 * 回收站移除
	 * 
	 * @param id
	 * @param viewState
	 * @param chestr
	 */
	@RequestMapping(value = "deleteTrash", method = RequestMethod.POST)
	public BossModel deleteTrash(
			String viewState,
			long id,
			@PageableDefault(page = 0, size = DEFAULT_PAGE_SIZE) Pageable pageable) {
		context.getGoodsRepository().delete(id);
		return createModel("goods/goods/trash/goodsTrash_table").add(
				"goodsPage", new Goods().findTrash(pageable)).add("viewState",
				viewState);
	}

	/**
	 * 还原
	 * 
	 * @param id
	 * @param viewState
	 * @param chestr
	 */
	@RequestMapping(value = "updateTrash", method = RequestMethod.POST)
	public BossModel updateTrash(
			String viewState,
			long id,
			@PageableDefault(page = 0, size = DEFAULT_PAGE_SIZE) Pageable pageable) {
		context.getGoodsRepository().updateTrash(id);
		return createModel("goods/goods/trash/goodsTrash_table").add(
				"goodsPage", new Goods().findTrash(pageable)).add("viewState",
				viewState);
	}

	/**
	 * 初始化进入商品搭配
	 * 
	 * @param goodsid
	 * @return
	 */
	@RequestMapping(value = "match/{goodsid}", method = RequestMethod.GET)
	public BossModel match(@PathVariable long goodsid, int page,
			String viewState) {
		GoodsSearchCondition searchCondition = new GoodsSearchCondition(
				goodsid, GoodsSearchCondition.SearchType.MATCH);
		return createModel("goods/goods/GoodsMatch")
				.add("searchCondition", searchCondition)
				.add("matchableGoods",
						context.getGoodsRepository().findAll(
								searchCondition
										.searchabledGoods(searchCondition)))
				.add("matchList",
						context.getGoodsRepository().findAll(
								context.getGoodsMatchRepository()
										.findMatchedGoodsIdByPrimaryGoodsId(
												goodsid)))
				.add("goodsId", goodsid)
				.add("matchedGoods", new GoodsMatch(goodsid))
				.add("brands", context.getBrandRepository().findAll())
				.add("categorys", context.getCategoryRepository().findAll())
				.add("page", page)
				.add("viewState", (viewState == null ? "" : viewState));
	}

	@RequestMapping(value = "selectableGoods", method = RequestMethod.POST)
	public @ResponseBody JSONArray goodsMatchableSearch(
			GoodsSearchCondition searchCondition) {
		List<Goods> list = context.getGoodsRepository().findAll(
				searchCondition.searchabledGoods(searchCondition));
		StringBuffer buffer = new StringBuffer("[");
		if (CollectionUtils.isNotEmpty(list)) {
			for (Goods goods : list) {
				buffer.append("{\"id\":\"" + goods.getId() + "\",\"name\":\""
						+ goods.getName() + "\"},");
			}
		}
		if (buffer.length() > 1) {
			buffer.deleteCharAt(buffer.length() - 1);
		}
		buffer.append("]");
		return JSONArray.fromObject(buffer.toString());
	}

	@RequestMapping(value = "saveGoodsMatch", method = RequestMethod.POST)
	@InitBinder(value = { "primaryGoodsId", "matchGoodsIds", "casCadeType" })
	public BossModel saveGoodsMatch(GoodsMatch matchedGoods, int page,
			String viewState, RedirectAttributes redirectAttributes) {

		// 数据库中已经关联的商品
		Set<Long> matchedGoodsIdsDB = context.getGoodsMatchRepository()
				.findMatchedGoodsIdByPrimaryGoodsId(
						matchedGoods.getPrimaryGoodsId());

		// 页面上传递过来的要关联的商品
		List<Long> matchedGoodsIdsFPage = new ArrayList<>();

		if (StringUtils.isNotBlank(matchedGoods.getMatchGoodsIds())) {
			for (String matchedGoodsId : matchedGoods.getMatchGoodsIds().split(
					",")) {
				matchedGoodsIdsFPage.add(Long.parseLong(matchedGoodsId));
			}
		}

		// 临时设置一个数据库已经搭配的商品id集合的副本
		Set<Long> copyOfmatchedGoodsIdsDB = new HashSet<>();
		copyOfmatchedGoodsIdsDB.addAll(matchedGoodsIdsDB);

		/**
		 * 页面上传递过来的就是保留下来的和新增的 数据库中的去掉与页面上相同的留下的就是页面上删除掉的 页面上的去掉数据库中相同的就是新增的
		 */

		matchedGoodsIdsDB.removeAll(matchedGoodsIdsFPage);// 数据库中移除与页面上相同的部分
															// 此时只剩下被移除的

		// 处理删除掉的
		if (CollectionUtils.isNotEmpty(matchedGoodsIdsDB)) {
			context.getGoodsMatchRepository().delete(
					context.getGoodsMatchRepository().findAll(
							matchedGoods.searchByPidAndMid(
									matchedGoods.getPrimaryGoodsId(),
									matchedGoodsIdsDB)));
		}

		if (matchedGoods.getCasCadeType().equals(GoodsMatch.CasCadeType.ONEWAY)) {// 单向关联
			// 处理页面上新增的
			matchedGoodsIdsFPage.removeAll(copyOfmatchedGoodsIdsDB);// 页面上移除与数据库中相同的部分
																	// 此时只剩下新增的
			if (CollectionUtils.isNotEmpty(matchedGoodsIdsFPage)) {
				for (Long id : matchedGoodsIdsFPage) {
					context.getGoodsMatchRepository()
							.save(new GoodsMatch(matchedGoods
									.getPrimaryGoodsId(), id));
				}
			}
		} else {// 双向关联
			if (CollectionUtils.isNotEmpty(matchedGoodsIdsFPage)) {
				List<Long> copyOfMatchedIdsFPage = new ArrayList<>();
				copyOfMatchedIdsFPage.addAll(matchedGoodsIdsFPage);
				copyOfMatchedIdsFPage.retainAll(copyOfmatchedGoodsIdsDB);// 原来已经保存于数据库中的
				matchedGoodsIdsFPage.removeAll(copyOfmatchedGoodsIdsDB);// 页面上新增的
				// 处理页面上原来已经搭配的 双向关联
				if (CollectionUtils.isNotEmpty(copyOfMatchedIdsFPage)) {
					for (Long id : copyOfMatchedIdsFPage) {
						if (CollectionUtils.isEmpty(context
								.getGoodsMatchRepository().checkByPidAndMid(id,
										matchedGoods.getPrimaryGoodsId()))) {
							context.getGoodsMatchRepository().save(
									new GoodsMatch(id, matchedGoods
											.getPrimaryGoodsId()));
						}
					}
				}
				// 处理页面上新增的
				if (CollectionUtils.isNotEmpty(matchedGoodsIdsFPage)) {
					for (Long id : matchedGoodsIdsFPage) {
						context.getGoodsMatchRepository().save(
								new GoodsMatch(
										matchedGoods.getPrimaryGoodsId(), id));
						context.getGoodsMatchRepository().save(
								new GoodsMatch(id, matchedGoods
										.getPrimaryGoodsId()));
					}
				}

			}

		}
		redirectAttributes.addFlashAttribute("message", context
				.getGoodsRepository().findOne(matchedGoods.getPrimaryGoodsId())
				.getName()
				+ "   搭配管理成功！");
		redirectAttributes.addAttribute("page", page);
		redirectAttributes.addAttribute("viewState",
				StringUtils.isNotBlank(viewState) ? viewState : "");
		return createModel("redirect:index");
	}

	/**
	 * input修改
	 * 
	 * @param goodsSN
	 * 
	 */
	@RequestMapping(value = "saveLine/{caId}/{newText}/{hidden_goodId}/{diff}", method = RequestMethod.POST)
	public BossModel saveLine(@PathVariable String caId,
			@PathVariable String newText, @PathVariable String hidden_goodId,
			@PathVariable String diff) {

		Album album = context.getAlbumRepository().findOne(Long.valueOf(caId));
		if ("picDer".equals(diff)) {
			album.setPicDescription(newText);
			context.getAlbumRepository().save(album);
		} else if ("picSort".equals(diff)) {
			album.setPicSort(Integer.valueOf(newText));
			context.getAlbumRepository().save(album);
		}
		List<Album> albumList = context.getAlbumRepository().findByGoodsId(
				Long.valueOf(hidden_goodId));
		return createModel("goods/goods/album/album_table").add("albums",
				albumList);

	}

	/**
	 * 放到回收站
	 * 
	 * @param id
	 * @param viewState
	 * @param chestr
	 */
	@RequestMapping(value = "delete", method = RequestMethod.POST)
	public BossModel delete(
			String viewState,
			String chestr,
			long id,
			@PageableDefault(page = 0, size = DEFAULT_PAGE_SIZE) Pageable pageable) {
		if (chestr != null) {
			String[] array = chestr.split(",");
			for (int i = 0; i < array.length; i++) {
				context.getGoodsRepository().findOne(Long.valueOf(array[i]))
						.delete();
			}
		} else {
			context.getGoodsRepository().findOne(id).delete();
		}
		// context.getGoodsRepository().findOne(id).delete();
		return createModel("goods/goods/goods_table").add("goodsPage",
				context.getGoodsRepository().findAll(pageable)).add(
				"viewState", viewState);
	}

	@RequestMapping(value = "updateState", method = RequestMethod.POST)
	public BossModel update(
			String viewState,
			String chestr,
			String status,
			String val,
			long id,
			RedirectAttributes redirectAttributes,
			@PageableDefault(page = 0, size = DEFAULT_PAGE_SIZE) Pageable pageable) {

		if ("up".equals(status) && chestr != null) {// 上架
			String[] array = chestr.split(",");
			for (int i = 0; i < array.length; i++) {
				Goods goods = context.getGoodsRepository().findOne(
						Long.valueOf(array[i]));
				goods.setDisplayed(true);
				context.getGoodsRepository().updateDisplayedTrue(
						goods.isDisplayed(), Long.valueOf(array[i]));
			}
		} else if ("down".equals(status) && chestr != null) {// 下架
			String[] array = chestr.split(",");
			for (int i = 0; i < array.length; i++) {
				Goods goods = context.getGoodsRepository().findOne(
						Long.valueOf(array[i]));
				goods.setDisplayed(false);
				context.getGoodsRepository().updateDisplayedTrue(
						goods.isDisplayed(), Long.valueOf(array[i]));
			}
		} else {
			Goods goods = context.getGoodsRepository().findOne(id);
			if (goods.isDisplayed() == true) {
				goods.setDisplayed(false);
				context.getGoodsRepository().updateDisplayedTrue(
						goods.isDisplayed(), id);
			} else {
				goods.setDisplayed(true);
				context.getGoodsRepository().updateDisplayedTrue(
						goods.isDisplayed(), id);
			}

		}
		return createModel("goods/goods/goods_table").add("goodsPage",
				context.getGoodsRepository().findAll(pageable)).add(
				"viewState", viewState);
	}

	@RequestMapping(value = "save", method = RequestMethod.POST)
	@InitBinder(value = { "name", "title", "goodsSN", "brandId", "categoryId",
			"shopPrice", "marketPrice", "goodsVideo", "content", "goodsStore",
			"reservedStore", "virtualSales", "realSales", "selectRecommends",
			"checkPic", "goodsTag", "displayed", "whether", "shortDescription",
			"goodsManageSort", "seokeywords" })
	public BossModel save(@Valid Goods goods,
			final BindingResult bindingResult,
			RedirectAttributes redirectAttributes,
			@RequestParam("goodImage") MultipartFile imgFile,
			@RequestParam("thumbImage") MultipartFile thumbfile,
			@RequestParam("longGoodsImage") MultipartFile longfile,
			@RequestParam("files") MultipartFile[] files)
			throws UnsupportedEncodingException {

		if (bindingResult.hasErrors()) {
			return createGoodsModel(null);
		}

		if (goods.getShopPrice().compareTo(goods.getMarketPrice()) > 0) {
			bindingResult.addError(new FieldError("goods", "shopPrice",
					"本店价格不能大于市场价格"));
			return createGoodsModel(goods);
		}

		if (goods.getBrandId() == 0) {
			bindingResult
					.addError(new FieldError("goods", "brandId", "请选择品牌名称"));
			return createGoodsModel(goods);
		}

		if (goods.getCategoryId() == 0) {
			bindingResult.addError(new FieldError("goods", "categoryId",
					"请选择商品分类"));
			return createGoodsModel(goods);
		}

		if (goods.getCheckPic() == null) {
			if (!imgFile.isEmpty() && !longfile.isEmpty()
					&& !thumbfile.isEmpty()) {
				String longpath1 = saveFile(longfile, goods.getGoodsSN());
				String goodspath = saveFile(imgFile, goods.getGoodsSN());
				String thumbpath = saveFile(thumbfile, goods.getGoodsSN());
				goods.setThumbGoodsPic(thumbpath);
				goods.setLongGoodsPic(longpath1);
				goods.setGoodsPic(goodspath);
			} else {
				if (imgFile.getSize() == 0 && goods.getGoodsPic() == null) {
					bindingResult.addError(new FieldError("goods", "goodsPic",
							"请选择商品图片"));
					return createGoodsModel(goods);
				} else if (imgFile.getSize() == 0
						&& goods.getGoodsPic().isEmpty()) {
					bindingResult.addError(new FieldError("goods", "goodsPic",
							"请选择商品图片"));
					return createGoodsModel(goods);
				} else if (longfile.getSize() == 0
						&& goods.getLongGoodsPic() == null) {
					bindingResult.addError(new FieldError("goods",
							"longGoodsPic", "请选择商品长图"));
					return createGoodsModel(goods);
				} else if (longfile.getSize() == 0
						&& goods.getLongGoodsPic().isEmpty()) {
					bindingResult.addError(new FieldError("goods",
							"longGoodsPic", "请选择商品长图"));
					return createGoodsModel(goods);
				} else if (thumbfile.getSize() == 0
						&& goods.getThumbGoodsPic() == null) {
					bindingResult.addError(new FieldError("goods",
							"thumbGoodsPic", "请选择商品缩略图"));
					return createGoodsModel(goods);
				} else if (thumbfile.getSize() == 0
						&& goods.getThumbGoodsPic().isEmpty()) {
					bindingResult.addError(new FieldError("goods",
							"thumbGoodsPic", "请选择商品缩略图"));
					return createGoodsModel(goods);
				} else if (thumbfile.getSize() > 0) {
					String thumbpath = saveFile(thumbfile, goods.getGoodsSN());
					goods.setThumbGoodsPic(thumbpath);
				} else if (longfile.getSize() > 0) {
					String longpath1 = saveFile(longfile, goods.getGoodsSN());
					goods.setLongGoodsPic(longpath1);
				} else if (imgFile.getSize() > 0) {
					String goodspath = saveFile(imgFile, goods.getGoodsSN());
					goods.setGoodsPic(goodspath);
				}
			}
		} else {

			if (!imgFile.isEmpty() && !longfile.isEmpty()) {
				String longpath1 = saveFile(longfile, goods.getGoodsSN());
				String goodspath = saveFile(imgFile, goods.getGoodsSN());
				String thumbpath1 = saveFile(imgFile, goods.getGoodsSN());
				goods.setThumbGoodsPic(thumbpath1);
				goods.setLongGoodsPic(longpath1);
				goods.setGoodsPic(goodspath);
			} else {
				if (imgFile.getSize() == 0 && goods.getGoodsPic() == null) {
					bindingResult.addError(new FieldError("goods", "goodsPic",
							"请选择商品图片"));
					return createGoodsModel(goods);
				} else if (imgFile.getSize() == 0
						&& goods.getGoodsPic().isEmpty()) {
					bindingResult.addError(new FieldError("goods", "goodsPic",
							"请选择商品图片"));
					return createGoodsModel(goods);
				} else if (longfile.getSize() == 0
						&& goods.getLongGoodsPic() == null) {
					bindingResult.addError(new FieldError("goods",
							"longGoodsPic", "请选择商品长图"));
					return createGoodsModel(goods);
				} else if (longfile.getSize() == 0
						&& goods.getLongGoodsPic().isEmpty()) {
					bindingResult.addError(new FieldError("goods",
							"longGoodsPic", "请选择商品长图"));
					return createGoodsModel(goods);
				} else if (imgFile.getSize() > 0) {
					String goodspath = saveFile(imgFile, goods.getGoodsSN());
					String thumbpath1 = saveFile(imgFile, goods.getGoodsSN());
					goods.setGoodsPic(goodspath);
					goods.setThumbGoodsPic(thumbpath1);
				} else if (longfile.getSize() > 0) {
					String longpath1 = saveFile(longfile, goods.getGoodsSN());
					goods.setLongGoodsPic(longpath1);
				}
			}
		}

		goods.init();
		String message = goods.getSucessFlashMessage();

		if (goods.getMark() != null && !"".equals(goods.getMark())) {

			goods = context.getGoodsRepository().findOne(
					Long.valueOf(goods.getMark()));
		} else {
			goods.save(goods);
		}

		if (goods.isDeleted() == true) {
			goods.setDeleted(false);
		}
		redirectAttributes.addFlashAttribute("message", message);
		return createGoods(goods, files, message);

	}

	private BossModel createGoods(Goods goods, MultipartFile[] files,
			String message) throws UnsupportedEncodingException {
		// /////////////////////////////以上是上传商品//////////////////////////////////

		// /////////////////////////////以下是商品规格//////////////////////////////////

		Category cate = context.getCategoryRepository().findOne(
				goods.getCategoryId());
		List<GoodsAttribute> goodsAttrs = context.getGoodsAttributeRepository()
				.findByGoodsId(goods.getId());
		if (cate.getAttributeIds() != null) {
			if (goodsAttrs.size() != 0) {
				List<String> oneListFirst = goods.getGoodsColorIdList();
				for (GoodsAttribute goodsAttr : goodsAttrs) {
					Attribute attr = context.getAttributeRepository()
							.findByInputValues(goodsAttr.getAttributeValues());
					if (!attr.getName().equals("颜色")
							|| !oneListFirst.contains(goodsAttr
									.getAttributeValues())) {
						context.getGoodsAttributeRepository().delete(
								goodsAttr.getId());
					}
				}

			}

		}

		// ////商品关联属性模块/////

		// ////唯一属性/////
		GoodsAttribute goodsAttributepic;
		if (goods.getSelelctList() != null) {
			List<String> selectList = goods.getSelelctList();
			for (int i = 0; i < selectList.size(); i++) {
				Attribute attrPic = context.getAttributeRepository()
						.findByInputValues(selectList.get(i));
				goodsAttributepic = new GoodsAttribute(goods.getId(),
						attrPic.getId(), selectList.get(i).trim(), attrPic
								.getName().trim(), "");
				context.getGoodsAttributeRepository().save(goodsAttributepic);
			}
		}

		// ////单选属性/////
		List<String> oneListFirst = goods.getGoodsColorIdList();
		List<String> oneList = goods.getGoodsColorList();
		Attribute attr = null;
		GoodsAttribute goodsAttribute = null;
		Attribute attrC = null;
		if (oneListFirst != null && oneListFirst.size() != 0) {
			attrC = context.getAttributeRepository().findByInputValues(
					oneListFirst.get(0));
		}
		List<String> oneListSecond = null;
		if (oneListFirst != null) {
			oneListSecond = new ArrayList<String>();
			for (int j = 0; j < oneList.size(); j++) {
				if (!oneList.get(j).isEmpty()) {
					oneListSecond.add(oneList.get(j));
				}
			}
			if ("颜色".equals(attrC.getName())) {
				for (int i = 0; i < oneListFirst.size(); i++) {
					attr = context.getAttributeRepository().findByInputValues(
							oneListFirst.get(i));
					MultipartFile file = files[i];
					if (goodsAttrs.size() != 0) {
						GoodsAttribute goodsAttr1 = context
								.getGoodsAttributeRepository()
								.findByAttributeValues(
										oneListFirst.get(i).toString(),
										goods.getId());
						if (goodsAttr1 != null) {
							goodsAttr1.setAttributeName(oneListSecond.get(i));
						} else {
							goodsAttr1 = new GoodsAttribute(goods.getId(),
									attr.getId(), oneListFirst.get(i),
									oneListSecond.get(i), "");
							context.getGoodsAttributeRepository().save(
									goodsAttr1);
						}
						if (file.getSize() != 0) {
							String path1 = saveFile(file, goods.getGoodsSN());
							goodsAttr1.setAtteibutePic(path1);
							context.getGoodsAttributeRepository().save(
									goodsAttr1);

						} else {
							continue;
						}

					} else {
						if (file.getSize() != 0) {
							String path2 = saveFile(file, goods.getGoodsSN());
							goodsAttribute = new GoodsAttribute(goods.getId(),
									attr.getId(), oneListFirst.get(i),
									oneListSecond.get(i), path2);
							context.getGoodsAttributeRepository().save(
									goodsAttribute);

						} else {
							goodsAttribute = new GoodsAttribute(goods.getId(),
									attr.getId(), oneListFirst.get(i),
									oneListSecond.get(i), "");
							context.getGoodsAttributeRepository().save(
									goodsAttribute);
						}
					}

				}
			} else {
				for (int i = 0; i < oneListFirst.size(); i++) {
					attr = context.getAttributeRepository().findByInputValues(
							oneListFirst.get(i));
					goodsAttribute = new GoodsAttribute(goods.getId(),
							attr.getId(), oneListFirst.get(i),
							oneListSecond.get(i), "");
					context.getGoodsAttributeRepository().save(goodsAttribute);
				}
			}
		}

		List<String> twoListFirst = goods.getGoodsSizeIdList();
		List<String> twoList = goods.getGoodsSizeList();
		List<String> twoListSecond = null;
		if (twoListFirst != null) {
			twoListSecond = new ArrayList<String>();
			for (int j = 0; j < twoList.size(); j++) {
				if (!twoList.get(j).isEmpty()) {
					twoListSecond.add(twoList.get(j));
				}
			}

			for (int i = 0; i < twoListFirst.size(); i++) {
				GoodsAttribute goodsAttrTwo = context
						.getGoodsAttributeRepository().findByAttributeValues(
								twoListFirst.get(i), goods.getId());
				if (goodsAttrTwo == null) {
					attr = context.getAttributeRepository().findByInputValues(
							twoListFirst.get(i));
					goodsAttribute = new GoodsAttribute(goods.getId(),
							attr.getId(), twoListFirst.get(i),
							twoListSecond.get(i), "");
					context.getGoodsAttributeRepository().save(goodsAttribute);
				} else {
					continue;
				}

			}

		}
		;

		// ////生成SKU/////

		List<SKU> skuList = new ArrayList<SKU>();
		SKU sku = null;
		if (oneListFirst != null && twoListFirst != null) {

			Attribute attrOne = context.getAttributeRepository()
					.findByInputValues(oneListFirst.get(0));
			Attribute attrTwo = context.getAttributeRepository()
					.findByInputValues(twoListFirst.get(0));
			String name = "";
			for (int i = 0; i < oneListFirst.size(); i++) {
				for (int j = 0; j < twoListFirst.size(); j++) {
					name = oneListFirst.get(i) + "," + twoListFirst.get(j);
					SKU skuname = context.getSkuRepository()
							.findByGoodsIdAndAttributeValues(goods.getId(),
									name);
					if (skuname != null) {
						String[] name1 = skuname.getGoodsAttributeValues()
								.split(",");
						skuname.setGoodsAttributeName(name1[0]);
						skuname.setGoodsAttributeValues(name1[1]);
						skuList.add(skuname);
					} else {
						sku = new SKU();
						sku.setGoodsAttributeName(oneListFirst.get(i));
						sku.setGoodsAttributeValues(twoListFirst.get(j));
						skuList.add(sku);
					}

				}

				goods.setSKUList(skuList);

			}
			message += ",请设置其SKU并提交！";
			return createModel("goods/goods/skuInfo").add("goods", goods)
					.add("attrOne", attrOne.getName())
					.add("attrTwo", attrTwo.getName()).add("message", message);
		} else if (oneListFirst != null && twoListFirst == null) {

			Attribute attrOne = context.getAttributeRepository()
					.findByInputValues(oneListFirst.get(0));
			String name = "";
			for (int i = 0; i < oneListSecond.size(); i++) {
				name = oneListFirst.get(i);
				SKU skuname = context.getSkuRepository()
						.findByGoodsIdAndAttributeValues(goods.getId(), name);
				if (skuname != null) {
					String name1 = skuname.getGoodsAttributeValues();
					skuname.setGoodsAttributeName(name1);
					skuList.add(skuname);
				} else {
					sku = new SKU();
					sku.setGoodsAttributeName(oneListFirst.get(i));
					skuList.add(sku);
				}
			}
			goods.setSKUList(skuList);
			message += ",请设置其SKU并提交！";
			return createModel("goods/goods/skuInfo").add("goods", goods)
					.add("attrOne", attrOne.getName()).add("message", message);

		} else {

			return findGoodsById(goods.getId(), new PageRequest(0, 15)).add(
					"message", message);// createModel("redirect:index");
		}
	}

	@RequestMapping(value = "saveSKU", method = RequestMethod.POST)
	public BossModel saveSKU(Goods goods) throws UnsupportedEncodingException {
		SKU sku;
		List<SKU> skuLists = context.getSkuRepository().findByGoodsId(
				goods.getId());
		for (int i = 0; i < skuLists.size(); i++) {
			context.getSkuRepository().delete(skuLists.get(i).getId());
		}
		long goodsStore = 0;
		if (CollectionUtils.isNotEmpty(goods.getSKUList())) {
			List<SKU> skuList = goods.getSKUList();
			for (int i = 0; i < skuList.size(); i++) {
				sku = new SKU();
				sku.setGoodsId(goods.getId());
				StringBuffer name = new StringBuffer();
				StringBuffer values = new StringBuffer();
				if (skuList.get(i).getGoodsAttributeName() != null) {
					GoodsAttribute name1 = context
							.getGoodsAttributeRepository()
							.findByAttributeValues(
									skuList.get(i).getGoodsAttributeName(),
									goods.getId());
					name.append(name1);
					values.append(skuList.get(i).getGoodsAttributeName());

				}

				if (skuList.get(i).getGoodsAttributeValues() != null) {
					GoodsAttribute name2 = context
							.getGoodsAttributeRepository()
							.findByAttributeValues(
									skuList.get(i).getGoodsAttributeValues(),
									goods.getId());
					name.append("," + name2);
					values.append(","
							+ skuList.get(i).getGoodsAttributeValues());
				}
				sku.setGoodsAttributeName(name.toString());
				sku.setGoodsAttributeValues(values.toString());
				sku.setSku_goodsSN(skuList.get(i).getSku_goodsSN());
				sku.setGoodsNum(skuList.get(i).getGoodsNum());
				goodsStore += skuList.get(i).getGoodsNum();
				sku.setGoodsPrice(skuList.get(i).getGoodsPrice());
				sku.setShapeCode(skuList.get(i).getShapeCode());
				context.getGoodsRepository().updateGoodsByGoodsSort(goodsStore,
						goods.getId());
				context.getSkuRepository().save(sku);

			}
		}

		String message = "设置"
				+ context.getGoodsRepository().findOne(goods.getId()).getName()
				+ "的sku成功！";
		if ("2".equals(goods.getMark())) {
			return createEditGoods(goods.getId());
		} else {
			return findGoodsById(goods.getId(), new PageRequest(0, 15)).add(
					"message", message);// createModel("redirect:index");
		}

	}

	@RequestMapping(value = "verifyGoodsSN")
	public @ResponseBody boolean verifyGoodsSN(Goods goods, String goodsId) {
		int num = context.getGoodsRepository()
				.findByGoodsSN(goods.getGoodsSN()).size();
		if (num != 0) {
			if (validation(goodsId)) {
				if (context.getGoodsRepository()
						.findOne(Long.parseLong(goodsId)).getGoodsSN()
						.equals(goods.getGoodsSN())) {
					return true;
				} else {
					return false;
				}
			} else {
				return false;
			}
		} else {
			return true;
		}

	}

	@RequestMapping(value = "verifySKuGoodsSN")
	public @ResponseBody boolean verifySKuGoodsSN(String skuGoodsSN) {
		SKU sku = context.getSkuRepository().findByGoodsSN(skuGoodsSN);
		if (sku != null) {

			if (context.getSkuRepository().findByGoodsSN(skuGoodsSN)
					.getSku_goodsSN().equals(skuGoodsSN)) {
				return true;
			} else {
				return false;
			}

		} else {
			return true;
		}

	}

	/***
	 * 保存文件
	 * 
	 * @param file
	 * @return
	 */
	private @ResponseBody() String saveFile(MultipartFile file, String goodsSN) {

		if (!file.isEmpty()) {
			try {
				/* 命名规则 */
				String pic_type = file.getContentType();
				String fileName;
				Random random = new Random();
				int x = random.nextInt(899999);
				int randomValue = x + 100000;

				String file_ture_name = goodsSN + "_" + new Date().getTime()
						+ randomValue;
				if (pic_type.equals("image/jpeg")) {
					fileName = file_ture_name.concat(".jpg");
				} else if (pic_type.equals("image/png")) {
					fileName = file_ture_name.concat(".png");
				} else if (pic_type.equals("image/bmp")) {
					fileName = file_ture_name.concat(".bmp");
				} else if (pic_type.equals("image/gif")) {
					fileName = file_ture_name.concat(".gif");
				} else {
					fileName = file_ture_name.concat(".jpg");
				}

				String returnMessage = FileUploadSupport.upload(
						file.getInputStream(), fileName, ImageType.GOODS);
				return returnMessage;
			} catch (Exception e) {
				return "";
			}
		} else {
			return "";
		}
	}

	private BossModel findGoodsById(
			long id,
			@PageableDefault(page = 0, size = DEFAULT_PAGE_SIZE, sort = "createdDate", direction = Direction.DESC) final Pageable pageable)
			throws UnsupportedEncodingException {
		GoodsSearch search = new GoodsSearch();
		List<Category> cateList = context.getCategoryRepository().findAll();
		/* cateList.add(0,new Category(0,"顶级分类")); */
		search.setGoodsId(String.valueOf(id));
		return createModel("/goods/goods/index")
				.add("goodsSearch", search)
				.add("goodsPage",
						context.getGoodsRepository().findAll(
								new Goods().selectCondition(search), pageable))
				.add("brands", context.getBrandRepository().findAll())
				.add("categorys", cateList)
				.add("viewState",
						Base64.getEncoder().encodeToString(
								JSONObject.fromObject(search).toString()
										.getBytes("UTF-8")));

	}

	private BossModel createGoodsModel(Goods goods) {
		List<Category> cateList = context.getCategoryRepository().findAll();
		cateList.add(0, new Category(0, "顶级分类"));
		BossModel modelAndView = createModel("goods/goods/info")
				.add("selectRecommends", Goods.SelectRecommend.values())
				.add("brands", context.getBrandRepository().findAll())
				.add("categorys", cateList);
		if (goods != null)
			modelAndView.add("goods", goods);
		return modelAndView;
	}

	private BossModel createEditGoods(long id) {

		Goods goods = new Goods().findOne(id);
		Category cate = context.getCategoryRepository().findOne(
				goods.getCategoryId());
		List<SKU> skuList = context.getSkuRepository().findByGoodsId(id);
		List<String> attrList = new ArrayList<String>();
		List<GoodsAttribute> goodsAttributeList = context
				.getGoodsAttributeRepository().findByGoodsId(id);
		List<String> goodsAttrList = new ArrayList<String>();
		for (GoodsAttribute goodAttr : goodsAttributeList) {
			Attribute attr = context.getAttributeRepository()
					.findByInputValues(goodAttr.getAttributeValues());
			if (attr.getName().equals("颜色")) {
				goodsAttrList.add(goodAttr.getAttributePic());
			}
		}

		String str = cate.getAttributeIds();
		String single = "";
		String only = "";
		if (str != null) {
			String[] strs = str.split(",");
			for (int i = 0; i < strs.length; i++) {
				Attribute attr = context.getAttributeRepository().findOne(
						Long.valueOf(strs[i]));
				if ("SINGLE" == attr.getSelectType().toString()) {
					single += strs[i] + ",";
				} else if ("ONLY" == attr.getSelectType().toString()) {
					only += strs[i] + ",";
				}
			}
		}
		// 单选属性
		Map<String, Map<String, String>> attrMapColor = new LinkedHashMap<String, Map<String, String>>();
		Map<String, List<String>> attrMapOne = new LinkedHashMap<String, List<String>>();
		Map<String, List<String>> attrMapTwo = new LinkedHashMap<String, List<String>>();
		Map<String, String> attrListColor = new LinkedHashMap<String, String>();
		List<String> attrListOne = new ArrayList<String>();
		List<String> attrListTwo = new ArrayList<String>();
		if (single.length() != 0) {
			String[] singleList = single.split(",");
			for (int j = 0; j < singleList.length; j++) {
				Attribute attr = context.getAttributeRepository().findOne(
						Long.valueOf(singleList[j]));
				if ("颜色".equals(attr.getName())) {
					String[] inputList = attr.getInputValues().split("\n");
					if (j == 0) {
						for (int k = 0; k < inputList.length; k++) {
							String[] inputColor = inputList[k].split(",");
							attrListColor.put(inputColor[0], inputColor[1]);
						}
						attrMapColor.put(attr.getName(), attrListColor);
					} else if (j == 1) {
						for (int l = 0; l < inputList.length; l++) {
							attrListTwo.add(inputList[l]);
						}
						attrMapTwo.put(attr.getName(), attrListTwo);
					}
				} else {
					String[] inputList = attr.getInputValues().split("\n");
					if (j == 0) {
						for (int k = 0; k < inputList.length; k++) {
							attrListOne.add(inputList[k]);
						}
						attrMapOne.put(attr.getName(), attrListOne);
					} else if (j == 1) {
						for (int l = 0; l < inputList.length; l++) {
							attrListTwo.add(inputList[l]);
						}
						attrMapTwo.put(attr.getName(), attrListTwo);
					}
				}

			}
		}
		// 唯一属性
		Map<String, List<String>> attrMapThree = new LinkedHashMap<String, List<String>>();
		List<String> attrListThree;
		if (only.length() != 0) {
			String[] onlyList = only.split(",");
			for (int i = 0; i < onlyList.length; i++) {
				Attribute attr = context.getAttributeRepository().findOne(
						Long.valueOf(onlyList[i]));
				String[] inputList = attr.getInputValues().split("\n");
				attrListThree = new ArrayList<String>();
				for (int j = 0; j < inputList.length; j++) {
					attrListThree.add(inputList[j].trim());
				}
				attrMapThree.put(attr.getName(), attrListThree);
			}
		}
		// 回显唯一属性
		List<GoodsAttribute> goodsAttribute = context
				.getGoodsAttributeRepository().findByGoodsId(goods.getId());
		Attribute attrOnly = null;
		List<String> onlyList = new ArrayList<String>();
		for (GoodsAttribute goodsAttr : goodsAttribute) {
			attrOnly = context.getAttributeRepository().findOne(
					Long.valueOf(goodsAttr.getAttributeId()));
			if ("ONLY" == attrOnly.getSelectType().toString()) {
				onlyList.add(goodsAttr.getAttributeValues());
			} else if ("SINGLE" == attrOnly.getSelectType().toString()) {
				attrList.add(goodsAttr.getAttributeName());
			}

		}
		String val = "edit";
		return createGoodsModel(goods).add("skuList", skuList)
				.add("attrList", attrList).add("goodsAttrList", goodsAttrList)
				.add("onlyList", onlyList).add("attrMapOne", attrMapOne)
				.add("attrMapColor", attrMapColor)
				.add("attrMapTwo", attrMapTwo)
				.add("attrMapThree", attrMapThree).add("val", val);

	}

	/**
	 * 后期进行自己扩展 可单独写一个验证类 对于String类型的参数 不为空且不是空字符串 对于list
	 * 
	 * @param obj
	 * @return
	 */
	private boolean validation(Object obj) {
		if (obj instanceof String) {
			obj = (String) obj;
			return obj != null && !obj.equals("");
		} else {
			return false;
		}
	}

}
